#!/bin/bash

# 加载配置
if [[ -f "build.config" ]]; then
    source build.config
else
    echo "错误: 未找到build.config文件"
    exit 1
fi

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 打印信息
info() {
    echo -e "${GREEN}[信息]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

error() {
    echo -e "${RED}[错误]${NC} $1"
    exit 1
}

# 创建必要的目录
create_dirs() {
    info "创建目录..."
    
    mkdir -p "${BUILD_DIR}" \
             "${COVERAGE_DIR}" \
             "${LOG_DIR}" \
             "${CACHE_DIR}" \
             "${BUILD_CACHE_DIR}" \
             "${MAVEN_CACHE_DIR}" \
             "${GRADLE_CACHE_DIR}" \
             "${TEMP_DIR}" \
             "${WORKSPACE_DIR}"

    info "目录创建完成"
}

# 检查Go环境
check_go() {
    info "检查Go环境..."
    if ! command -v go &> /dev/null; then
        error "Go未安装，请先安装Go"
    fi

    GO_CURRENT_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
    if [[ "${GO_CURRENT_VERSION}" < "${GO_VERSION}" ]]; then
        error "Go版本过低，需要${GO_VERSION}或更高版本"
    fi

    info "Go版本: ${GO_CURRENT_VERSION}"
}

# 初始化项目
init_project() {
    info "初始化项目..."
    
    # 初始化Go模块
    if [[ ! -f "go.mod" ]]; then
        go mod init ${PROJECT_NAME} || error "初始化Go模块失败"
    fi

    # 下载依赖
    go mod tidy || error "下载依赖失败"

    info "初始化完成"
}

# 代码检查
check_code() {
    info "检查代码..."
    
    # 格式化代码
    go fmt ./... || warn "代码格式化失败"

    # 代码检查
    go vet ./... || warn "代码检查发现问题"

    info "代码检查完成"
}

# 运行测试
run_tests() {
    info "运行测试..."
    
    # 运行测试
    go test -v -race -timeout="${TEST_TIMEOUT}" -coverprofile="${COVERAGE_FILE}" ./... || error "测试失败"

    # 生成覆盖率报告
    go tool cover -html="${COVERAGE_FILE}" -o "${COVERAGE_HTML}"

    # 检查覆盖率
    COVERAGE=$(go tool cover -func="${COVERAGE_FILE}" | grep total | awk '{print $3}' | sed 's/%//')
    if (( $(echo "${COVERAGE} < ${COVERAGE_THRESHOLD}" | bc -l) )); then
        warn "测试覆盖率 ${COVERAGE}% 低于目标 ${COVERAGE_THRESHOLD}%"
    else
        info "测试覆盖率: ${COVERAGE}%"
    fi

    info "测试完成"
}

# 构建项目
build_binary() {
    info "构建项目..."
    
    # 设置环境变量
    export CGO_ENABLED=${CGO_ENABLED}
    export GOOS=${GOOS}
    export GOARCH=${GOARCH}

    # 构建二进制文件
    go build \
        -ldflags "${LDFLAGS}" \
        -o "${BUILD_DIR}/${PROJECT_NAME}" \
        "${MAIN_FILE}" || error "构建失败"

    info "构建完成: ${BUILD_DIR}/${PROJECT_NAME}"
    info "版本: ${VERSION}"
    info "提交: $(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')"
    info "时间: $(date '+%Y-%m-%d %H:%M:%S')"
}

# 清理旧文件
cleanup() {
    info "清理旧文件..."
    
    # 清理超过指定时间的日志
    find "${LOG_DIR}" -type f -mtime "+${CLEANUP_AGE}" -delete 2>/dev/null || true

    # 清理超过大小限制的缓存
    if command -v du &> /dev/null; then
        CACHE_SIZE=$(du -sb "${CACHE_DIR}" 2>/dev/null | cut -f1)
        if [[ ${CACHE_SIZE} -gt ${MAX_CACHE_SIZE} ]]; then
            warn "缓存大小超过限制，执行清理..."
            rm -rf "${CACHE_DIR:?}"/*
        fi
    fi

    info "清理完成"
}

# 主函数
main() {
    echo "${DESCRIPTION}"
    echo "================="

    # 执行构建步骤
    cleanup
    create_dirs
    check_go
    init_project
    check_code
    run_tests
    build_binary

    echo "================="
    info "构建成功！"
    info "二进制文件位置: ${BUILD_DIR}/${PROJECT_NAME}"
    info "执行 './${BUILD_DIR}/${PROJECT_NAME} --help' 查看使用说明"
}

# 执行主函数
main
